package me.obstsalat.guildera;

import org.bukkit.block.Block;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.IronGolem;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;

public class g_irongolem {
	private guildera plugin;
	
	g_irongolem(guildera pl) {
		plugin = pl;
	}
	
	public boolean onEntityDamagebyEntity(EntityDamageByEntityEvent event) {
		if(!plugin.checkViableWorld(event.getEntity().getWorld())) {
			return false;
		}
		if(event.getEntityType() == EntityType.VILLAGER || event.getEntityType() == EntityType.IRON_GOLEM) {
			for(guild g : plugin.guilds) {
				if(g.isInGuild(event.getEntity().getLocation()) && event.getEntity().getLocation().getWorld().getName().equals(plugin.overworld.getName())) {
					for(Entity ent : plugin.overworld.getEntities()) {
						if(ent.getType() == EntityType.IRON_GOLEM) {
							long dx = ent.getLocation().getBlockX() - event.getDamager().getLocation().getBlockX();
							long dz = ent.getLocation().getBlockZ() - event.getDamager().getLocation().getBlockZ();
							if(((dx*dx) < (50*50)) && ((dz*dz) < (50*50))) {
								IronGolem cent = (IronGolem)ent;
								if(event.getDamager().getType() == EntityType.PLAYER) {
									cent.setTarget((LivingEntity) event.getDamager());
								} else if(event.getDamager().getType() == EntityType.ARROW) {
									Arrow ar = (Arrow)event.getDamager();
									cent.setTarget(ar.getShooter());
								}
								
							}
						}
					}
				}
			}
		}
		return false;
	}
					
	
	public boolean onBlockBreak(BlockBreakEvent event) {
		Block bl = event.getBlock();
		if(!plugin.checkViableWorld(bl.getWorld())) {
			return false;
		}
		if(!plugin.overworld.getName().equals(event.getBlock().getWorld().getName())) {
			return false;
		}
		if(!event.getPlayer().isOp()) {
			for(guild g : plugin.guilds) {
				if(g.isInGuild(bl.getLocation()) && !g.hasMember(event.getPlayer().getName())) {
					for(Entity ent : plugin.overworld.getEntities()) {
						if(ent.getType() == EntityType.IRON_GOLEM) {
							long dx = ent.getLocation().getBlockX() - bl.getX();
							long dz = ent.getLocation().getBlockZ() - bl.getZ();
							if(((dx*dx) < (50*50)) && ((dz*dz) < (50*50))) {
								IronGolem cent = (IronGolem)ent;
								cent.setTarget(event.getPlayer());
							}
						}
					}
				}
			}
		}
		return false;
	}
}
